<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="dongbu.bo.overtime.OverTimeBO"%>
<%@page import="java.util.List"%>
<%@page import="org.json.simple.JSONArray"%>
<%@page import="dongbu.vo.overtime.OverTimeChild"%>
<%
	request.setCharacterEncoding("UTF-8");

	OverTimeBO bo = new OverTimeBO();
	List childList = bo.getOverTimeChildList();
%>
<html>
	<head>
		<title>Input</title>
		<link rel="stylesheet" href="/Dongbu/lib/jquery-ui-1.8.18/css/demos.css">
		<link rel="stylesheet" href="/Dongbu/lib/jquery-ui-1.8.18/css/ui-lightness/jquery.ui.all.css">
		<link rel="stylesheet" href="/Dongbu/lib/jquery-ui-1.8.18/css/ui-lightness/jquery-ui-1.8.18.custom.css">
		<link rel='stylesheet' type='text/css' href='/Dongbu/lib/fullcalendar/fullcalendar.css' />
		<link rel='stylesheet' type='text/css' href='/Dongbu/lib/fullcalendar/fullcalendar.print.css' media='print' />
		
		<style type="text/css" media="all">@import "/Dongbu/lib/timePicker/timePicker.css";</style>
		
		<script src="/Dongbu/lib/jquery-ui-1.8.18/js/jquery-1.7.1.min.js"></script>
		<script src="/Dongbu/lib/jquery-ui-1.8.18/js/jquery-ui-1.8.18.custom.min.js"></script>
		<script src="/Dongbu/lib/jquery-ui-1.8.18/js/jquery.json-2.3.min.js"></script>
		<script type='text/javascript' src='/Dongbu/lib/fullcalendar/fullcalendar.js'></script>
		
		<script type="text/javascript" src="/Dongbu/lib/timePicker/jquery.timePicker.js"></script>
		<script>
			$(function() {
				$( "#dialog" ).dialog();
				
				var childName = $( "#childName" ),
				    childId   = $( "#childId" ),
					writeDate = $( "#writeDate" ),
					enterTime = $( "#enterTime" ),
					outTime   = $( "#outTime" ),
					allFields = $( [] ).add( writeDate ).add( enterTime ).add( childId ).add( childName ).add( outTime ),
					tips = $( ".validateTips" );
				
				var view_childName = $( "#view_childName" ),
		        	view_childId   = $( "#view_childId" ),
					view_writeDate = $( "#view_writeDate" ),
					view_enterTime = $( "#view_enterTime" ),
					view_outTime   = $( "#view_outTime" )
				
				$( "#dialog-form" ).dialog({
					autoOpen: false,
					height: 300,
					width: 350,
					modal: true,
					buttons: {
						"등록": function() {
							var bValid = true;
							allFields.removeClass( "ui-state-error" );

							if ( bValid ) {
								var addEvent = {
												id	 :'new', 
												title: childName.val(),
												start: writeDate.val() + " " + $( "#enterTime" ).val() ,
												end  : writeDate.val() + " " + $( "#outTime" ).val(),
												allDay: false
								};
								
								//저장
								$.ajax( { 
									type :'POST' 
									,asyn :true 
									,url :'/Dongbu/sample/jquery/save.jsp' 
									,data: 'addEvent='+$.toJSON(addEvent) 
									,dataType :"json" 
									,contentType :"application/x-www-form-urlencoded;charset=UTF-8" 
									,beforeSend : function(xhr){}				
									,success : function(jsonData) { 
										var resultId = jsonData.sendResult;
										if(resultId != ''){
											addEvent.id = resultId;
											$('#calendar').fullCalendar('renderEvent', addEvent, true);
										} else {
											alert("전송된 건이 없습니다.");
										}
									}
									,error : function(xhr, textStatus) {
										alert("전송중 오류가 발생했습니다.");				
									}
									,complete : function(xhr, textStatus) {
									}
								 }); 
								
								$('#calendar').fullCalendar('unselect');
								$( this ).dialog( "close" );
							}
						},
						"취소": function() {
							$( this ).dialog( "close" );
						}
					},
					close: function() {
						allFields.val( "" ).removeClass( "ui-state-error" );
					}
				});
				
				$( "#dialog-view" ).dialog({
					autoOpen: false,
					height: 300,
					width: 350,
					modal: true,
					buttons: {
						"수정": function() {
							
							var view_childName = $( "#view_childName" ),
								view_childId   = $( "#view_childId" ),
								view_writeDate = $( "#view_writeDate" ),
								view_enterTime = $( "#view_enterTime" ),
								view_outTime   = $( "#view_outTime" )
							
							var tmpEvent = $('#calendar').fullCalendar( 'clientEvents', view_childId.val());
							tmpEvent[0].title = view_childName.val();
							tmpEvent[0].start = view_writeDate.val() + " " + view_enterTime.val();
							tmpEvent[0].end   = view_writeDate.val() + " " + view_outTime.val();
							
							$('#calendar').fullCalendar('updateEvent', tmpEvent[0]);
							$( this ).dialog( "close" );
						},
						"삭제": function() {
							$('#calendar').fullCalendar( 'removeEvents' , $( "#view_childId" ).val() );
							$( this ).dialog( "close" );
						},
						"닫기": function() {
							$( this ).dialog( "close" );
						}
					},
					close: function() {
						allFields.val( "" ).removeClass( "ui-state-error" );
					}
				});
				
				 $(document).keyup(function(e){
				    var el = e.srcElement ? e.srcElement : e.target;
				    
				    if($(el).is(":text[keyEnter='Y']") || el.id=='dialog-view' || el.id=='dialog-form'){ //enter=Y인 것.
				    	if(e.which == 13){
				     		var view_childName = $( "#view_childName" ),
								view_childId   = $( "#view_childId" ),
								view_writeDate = $( "#view_writeDate" ),
								view_enterTime = $( "#view_enterTime" ),
								view_outTime   = $( "#view_outTime" )
							
							var tmpEvent = $('#calendar').fullCalendar( 'clientEvents', view_childId.val());
							tmpEvent[0].title = view_childName.val();
							tmpEvent[0].start = view_writeDate.val() + " " + view_enterTime.val();
							tmpEvent[0].end   = view_writeDate.val() + " " + view_outTime.val();
							
							$('#calendar').fullCalendar('updateEvent', tmpEvent[0]);
							$('#dialog-view').dialog( "close" );
				     	}
				    }
				   });
								
				
				$("#enterTime").timePicker({
					  startTime: "09:00",  // Using string. Can take string or Date object.
					  endTime: new Date(0, 0, 0, 11, 30, 0),  // Using Date object.
					  show24Hours: true,
					  separator:':',
					  step: 5
				});
				$("#outTime").timePicker({
					  startTime: "18:00",
					  endTime: new Date(0, 0, 0, 23, 30, 0),  
					  show24Hours: true,
					  separator:':',
					  step: 5
				});
				$("#view_enterTime").timePicker({
					  startTime: "09:00",  // Using string. Can take string or Date object.
					  endTime: new Date(0, 0, 0, 11, 30, 0),  // Using Date object.
					  show24Hours: true,
					  separator:':',
					  step: 5
				});
				$("#view_outTime").timePicker({
					  startTime: "18:00",
					  endTime: new Date(0, 0, 0, 23, 30, 0),  
					  show24Hours: true,
					  separator:':',
					  step: 5
				});
				
				$("#calculate").click(function(){
					var allEvents = $('#calendar').fullCalendar( 'clientEvents');
					var childNames = $("input[name='childname']");
					var result = '';
					
					var totalHour = 0, totalMinute = 0;
					
					for(i = 0 ; i < childNames.length ; i++){
						var sumHour = 0, sumMinute = 0;
						
						for(j = 0 ; j < allEvents.length ; j++){
							//이미 한 번 계산이 된 이름이라면 변경이 됐을 테니 다시 원복해준다.
							allEvents[j].title = allEvents[j].title.split(' ')[0];
							
							if(childNames[i].value == allEvents[j].title){
								//아동별 시간합계
								var endHour 	= $.fullCalendar.formatDate( allEvents[j].end, 'HH');
								var endMinute 	= $.fullCalendar.formatDate( allEvents[j].end, 'mm');
								
								if(endHour-19 >= 0){
									sumHour 	= sumHour + (endHour-19);
									sumMinute 	= sumMinute + parseInt(endMinute);
									
									allEvents[j].title = allEvents[j].title + " " + (endHour-19) + ":" + endMinute;
									$('#calendar').fullCalendar('updateEvent', allEvents[j]);
								}
							}
						}
						
						if( sumMinute >= 60){
							var incHour = parseInt(sumMinute / 60);
							sumMinute = sumMinute % 60;
							sumHour = sumHour + incHour;
						}
						
						totalHour = totalHour + sumHour;
						totalMinute = totalMinute + sumMinute;
						if(totalMinute >= 60){
							var incHour = parseInt(totalMinute / 60);
							totalMinute = totalMinute % 60;
							totalHour = totalHour + incHour;
						}
						
						result += (childNames[i].value + "은 " + sumHour +":" + sumMinute) + "<br>";
					}
					
					result += ("총계는 " + totalHour +":" + totalMinute) + "<br>";
										
					$("#calculate_result").html(result);
					$("#calculate_result" ).dialog();
				});
			});
			
			$(document).ready(function() {
				var calendar = $('#calendar').fullCalendar({
					header: {
						left: 'prev,next today',
						center: 'title',
						right: 'month,agendaWeek,agendaDay'
					},
					selectable: true,
					selectHelper: true,
					select: function(start, end, allDay) {
						$( "#writeDate" ).val($.fullCalendar.formatDate( start, 'yyyy-MM-dd'));
						$( "#childName").val('테스트');
						$( "#dialog-form" ).dialog( "open" );
					},
					
					editable: true,
					events: 'getDefaultTime.jsp',
					
					eventDrop: function(event, delta) {
						alert(event.id + ' was moved ' + delta + ' days\n' + '(should probably update your database)');
					},
					
					loading: function(bool) {
						if (bool) $('#loading').show();
						else $('#loading').hide();
					},

				    eventClick: function(calEvent, jsEvent, view) {
				        var view_childName = $( "#view_childName" ),
				        	view_childId   = $( "#view_childId" ),
							view_writeDate = $( "#view_writeDate" ),
							view_enterTime = $( "#view_enterTime" ),
							view_outTime   = $( "#view_outTime" )
							allFields = $( [] ).add( view_writeDate ).add( view_childId ).add( view_childName ).add( view_enterTime ).add( view_outTime );

						view_childId.val(calEvent.id);
				        view_childName.val(calEvent.title);
						view_writeDate.val($.fullCalendar.formatDate( calEvent.start, 'yyyy-MM-dd'));
						view_enterTime.val($.fullCalendar.formatDate( calEvent.start, 'HH:mm'));
						view_outTime.val($.fullCalendar.formatDate( calEvent.end, 'HH:mm'));
						
						$( "#dialog-view" ).dialog( "open" );					
				    },
				    nextClick: function() {
				    	//다음달 버튼을 누루면 해당 정보를 추가로 가져오도록 해볼까? 말까...
				        //$('#calendar').fullCalendar( 'addEventSource', '/Dongbu/sample/fullcal/response.jsp' );
				    }
				});
			});
		</script>
		<style>
			.ui-datepicker-calendar {display: none;}
			label, input { display:block; }
			input.text { margin-bottom:12px; width:95%; padding: .4em; }
			fieldset { padding:0; border:0; margin-top:25px; }
			h1 { font-size: 1.2em; margin: .6em 0; }
			div#users-contain { width: 350px; margin: 20px 0; }
			div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
			div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
			.ui-dialog .ui-state-error { padding: .3em; }
			.validateTips { border: 1px solid transparent; padding: 0.3em; }
			#calendar {
				width: 900px;
				margin: 0 auto;
				font-size: 14px;
				font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
			}
		</style>
	</head>
	<body>
		<form name="frmMain">
		<%
			if(childList != null && childList.size() > 0) {
				for(int i = 0 ; i < childList.size() ; i++){
					String childName = ((OverTimeChild)childList.get(i)).getName();
					out.println("<input type='hidden' name='childname' value='"+ childName +"'>");
				}
			}
		%>
		</form>
		
			<div id="dialog" title="Basic dialog">
				<p>FULLCALENDAR + JQUERY UI</p>
			</div>
			<div id="calculate_result" title="시간계산 결과"></div>
			
			<table class="layout-grid" cellspacing="0" cellpadding="0">
			<tr>
				<td class="left-nav">
					<dl class="demos-nav">
						<dt>해야할 리스트</dt>
							<dd><a href="#">인원설정</a></dd>
							<dd><a href="#">인원 이름 입력</a></dd>
							<dd><a href="#">인원별 시간입력</a></dd>
							<dd id="calculate"><a href="#">시간계산</a></dd>
					</dl>
				</td>
				<td class="normal">
					<div id='loading' style='display:none'>loading...</div>
					<div id='calendar'></div>
				</td>
			</tr>
			</table>
			<div class="demo">
				<div id="dialog-form" title="등록" keyEnter='Y'>
					<p class="validateTips">다 입력</p>
				
					<fieldset>
						<label for="childName">아동</label>
						<input type="text" name="childName" id="childName" value="" class="text ui-widget-content ui-corner-all" keyEnter='Y'/>
						<label for="writeDate">일자</label>
						<input type="text" name="writeDate" id="writeDate" class="text ui-widget-content ui-corner-all" keyEnter='Y'/>
						<input type="checkbox" name="absent" id="absent" >
						<label for="enterTime">등원</label>
						<div><input type="text" name="enterTime" id="enterTime" class="text ui-widget-content ui-corner-all" keyEnter='Y'/></div>
						<label for="outTime">퇴원</label>
						<div><input type="text" name="outTime" id="outTime" class="text ui-widget-content ui-corner-all" keyEnter='Y'/></div>
					</fieldset>
				</div>
				<div id="dialog-view" title="조회" keyEnter='Y'>
					<form name="frmInput">
					<fieldset>
						<label for="childName">아동</label>
						<input type="hidden" name="childId" id="view_childId"/>
						<input type="text" name="childName" id="view_childName" value="dddd" class="text ui-widget-content ui-corner-all" keyEnter='Y'/>
						<label for="writeDate">일자</label>
						<input type="text" name="writeDate" id="view_writeDate" class="text ui-widget-content ui-corner-all" keyEnter='Y'/>
						<label for="enterTime">등원</label>
						<div><input type="text" name="enterTime" id="view_enterTime" class="text ui-widget-content ui-corner-all" keyEnter='Y'/></div>
						<label for="outTime">퇴원</label>
						<div><input type="text" name="outTime" id="view_outTime" class="text ui-widget-content ui-corner-all" keyEnter='Y'/></div>
					</fieldset>
					</form>
				</div>
			</div>
	</body>
</html>